'''
Created on 2012-8-27

@author: demo of baidu
'''
import sys
import string
import time
import socket
import os


# Imports the monkeyrunner modules used by this program
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice, MonkeyImage 

# Connects to the current device, returning a MonkeyDevice object
device = MonkeyRunner.waitForConnection()
if not device:
    print "Please connect a device to start!"
else:
    print "waitForConnection ok"

######################################
# time function for show current time
######################################
def tell_time_now():
    print time.strftime('%Y-%m-%d-%H-%M-%S',time.localtime(time.time()))
            

######################################
# parser function 
######################################
def get_totallen_cmdlen_cmd_paranum_parserlen(buf):
    totallen = string.atoi(buf[1:4],10)
    print 'get_cmdlen_cmd_parserlen totallen',totallen
    cmdlen = string.atoi(buf[5:8],10)
    print 'get_cmdlen_cmd_parserlen cmdlen',cmdlen
    cmdend = 8+cmdlen
    print 'get_cmdlen_cmd_parserlen cmdend',cmdend
    commond = buf[8:cmdend]
    print 'get_cmdlen_cmd_parserlen commond',commond
    paranum = string.atoi(buf[8+cmdlen+1:8+cmdlen+4],10)
    print 'get_cmdlen_cmd_parserlen paranum',paranum
    parselen = 12+cmdlen
    print 'get_cmdlen_cmd_parserlen parselen',parselen
    return(totallen,cmdlen,commond,paranum,parselen)

def getparameter(buf,parsedlen):
#    print buf
#    print parsedlen    
    parlen = string.atoi(buf[parsedlen+1:parsedlen+4],10)
    par = buf[parsedlen+4:parsedlen+4+parlen]
    parselen = parsedlen+4+parlen
#    print parlen
#    print par
    return (parlen,par,parselen)

def init_rsp(cmdback):
    rspbuf = '0000'
    rspbuf += '%04d'%(len(cmdback))
    rspbuf += cmdback
    rspbuf += '%04d'%(0)
    rspbuflen = 12+ len(cmdback)
    return (rspbuf,rspbuflen)
    
def add_elem(elem,elemlen,paranumbegin,rspbuf,rspbuflen):
    paranum = string.atoi(rspbuf[paranumbegin-4:paranumbegin])
    paranum += 1
    rspbuf = rspbuf[:paranumbegin-4] +  '%04d'%(paranum) + rspbuf[paranumbegin+1:]        
    newrspbuflen = rspbuflen + 4
    newrspbuf = rspbuf + '%04d'%(elemlen)
     
    newrspbuf = newrspbuf + elem   
    newrspbuflen = newrspbuflen + elemlen

    newrspbuf = '%04d'%(newrspbuflen) + newrspbuf[4:]
    print newrspbuf
    return (newrspbuf,newrspbuflen)
######################################
# socket handle function 
######################################

port = 8001
listen_number = 16
wait_length = 9999
buf_recv = 128
buf_send = 1024
                            
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('localhost', port))
sock.listen(listen_number) 
print 'socket listening localhost',port
    
while True:    
    print 'socket wait connect.......'
    connection,address = sock.accept()  
    print address  
    try: 
        connection.settimeout(wait_length) 
        buf = connection.recv(buf_recv)  
        if not buf: break
#        print buf    
        tell_time_now();
        totallen,cmdlen,commond,paranum,parselen = get_totallen_cmdlen_cmd_paranum_parserlen(buf)
        print commond
        rspbuf,rspbuflen = init_rsp(commond)
#        print rspbuf
#        print rspbuflen   
        paranumbegin = rspbuflen  
        if commond == 'install': 
            if(1 != paranum):
                rspbuf,rspbuflen = add_elem("FAIL",4,paranumbegin,rspbuf,rspbuflen)
            else:
                apknamelen,apkname,parselen = getparameter(buf,parselen)
                print parselen
                print apkname
                print apknamelen
                apkresult = device.installPackage(apkname) 
                print apkresult 
                if apkresult:
                    rspbuf,rspbuflen = add_elem("PASS",4,paranumbegin,rspbuf,rspbuflen)
                else:
                    rspbuf,rspbuflen = add_elem("FAIL",4,paranumbegin,rspbuf,rspbuflen)
        elif commond == 'uninstall': 
            if(1 != paranum):
                rspbuf,rspbuflen = add_elem("FAIL",4,paranumbegin,rspbuf,rspbuflen)
            else:             
                apknamelen,apkname,parselen = getparameter(buf,parselen)
                print parselen
                print apkname
                print apknamelen            
                apkresult=device.removePackage(apkname)
                print apkresult  
                if apkresult:
                    rspbuf,rspbuflen = add_elem("PASS",4,paranumbegin,rspbuf,rspbuflen)
                else:
                    rspbuf,rspbuflen = add_elem("FAIL",4,paranumbegin,rspbuf,rspbuflen)         
        elif commond == 'touch':
            if(2 != paranum):
                rspbuf,rspbuflen = add_elem("FAIL",4,paranumbegin,rspbuf,rspbuflen)
            else:              
                xlen,x,parselen = getparameter(buf,parselen)
                print parselen
                print x
                print xlen  
                ylen,y,parselen = getparameter(buf,parselen)
                print parselen
                print y
                print ylen
                device.touch(string.atoi(x),string.atoi(y),"DOWN_AND_UP")                           
                rspbuf,rspbuflen = add_elem("PASS",4,paranumbegin,rspbuf,rspbuflen) 
        elif commond == 'drag':  
            if(4 != paranum):
                rspbuf,rspbuflen = add_elem("FAIL",4,paranumbegin,rspbuf,rspbuflen)
            else:             
                x1len,x1,parselen = getparameter(buf,parselen)
                y1len,y1,parselen = getparameter(buf,parselen) 
                x2len,x2,parselen = getparameter(buf,parselen)  
                y2len,y2,parselen = getparameter(buf,parselen)

                device.drag((string.atoi(x1),string.atoi(y1)),(string.atoi(x2),string.atoi(y2)),0.1,1)                        
                rspbuf,rspbuflen = add_elem("PASS",4,paranumbegin,rspbuf,rspbuflen)
        elif commond == 'snap': 
            if(1 != paranum):
                rspbuf,rspbuflen = add_elem("FAIL",4,paranumbegin,rspbuf,rspbuflen)
            else:            
                picnamelen,picname,parselen = getparameter(buf,parselen)
                print parselen
                print picname
                print picnamelen
                result = device.takeSnapshot()
                result.writeToFile(picname+'.png','png')              
                rspbuf,rspbuflen = add_elem("PASS",4,paranumbegin,rspbuf,rspbuflen)     
        elif commond == 'key': 
            if(1 != paranum):
                rspbuf,rspbuflen = add_elem("FAIL",4,paranumbegin,rspbuf,rspbuflen)
            else:            
                keylen,key,parselen = getparameter(buf,parselen)
                print keylen
                print key
                print parselen
                if key == 'MENU':
                    print key                	 
                    device.press('KEYCODE_MENU','DOWN_AND_UP')      
                elif key == 'BACK': 
                    print key                 	
                    device.press('KEYCODE_BACK','DOWN_AND_UP') 
                elif key == 'HOME': 
                    print key                 	
                    device.press('KEYCODE_HOME','DOWN_AND_UP')
                elif key == 'SEARCH':
                    print key                 	 
                    device.press('KEYCODE_SEARCH','DOWN_AND_UP')
                elif key == 'CAMERA':
                    print key                 	 
                    device.press('KEYCODE_CAMERA','DOWN_AND_UP')
                elif key == 'VOLUP': 
                    print key                 	
                    device.press('KEYCODE_VOLUME_UP','DOWN_AND_UP')
                elif key == 'VOLDOWN': 
                    print key                 	
                    device.press('KEYCODE_VOLUME_DOWN','DOWN_AND_UP')
                elif key == 'POWER': 
                    print key                 	
                    device.press('KEYCODE_POWER','DOWN_AND_UP')
                else: 
                    rspbuf,rspbuflen = add_elem("FAIL",4,paranumbegin,rspbuf,rspbuflen)                                                                                                                                                                                                      
                rspbuf,rspbuflen = add_elem("PASS",4,paranumbegin,rspbuf,rspbuflen)  
        elif commond == 'adbcmd': 
            if(1 != paranum):
                rspbuf,rspbuflen = add_elem("FAIL",4,paranumbegin,rspbuf,rspbuflen)
            else:   
                cmdlen,cmd,parselen = getparameter(buf,parselen)
                print cmdlen
                print cmd
                print parselen            	
                os.system(cmd)             	
                rspbuf,rspbuflen = add_elem("PASS",4,paranumbegin,rspbuf,rspbuflen)            	                           
        else:
            rspbuf,rspbuflen = add_elem("FAIL",4,paranumbegin,rspbuf,rspbuflen)
        connection.send(rspbuf)               
    except socket.timeout:
        print 'monkey socket connect time out'
    print 'socket close after send'    
    connection.close()    
print 'monkey socket disconnect abnormal transfer'    
connection.close()    

